﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using System.Configuration;

using ZedGraph;


namespace Predictor_v._1._0
{
    public partial class Predictor : Form
    {
        private PointPairList _loadedDataPairList;
        private double _alphaValue;
        private string _sheetName;
        private string _dataColumnName;
        private string _fileName;
        private GraphPane _pane;

        private ZedGraph.PointPairList _prediction;


        public Predictor()
        {
            InitializeComponent();
            _loadedDataPairList = new PointPairList();
            _alphaValue = Convert.ToDouble(ConfigurationManager.AppSettings["alphaValue"]);
            _sheetName = ConfigurationManager.AppSettings["sheetName"];
            _dataColumnName = ConfigurationManager.AppSettings["dataColumnName"];
            _fileName = "";
            _pane = zedGraph.GraphPane;
        }

        private void loadDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_fileName == "")
            {
                SelectFileToLoadData();
            }
            if (_fileName != "")
            {
                GetDataFromXls();
            }
        }

        private void loadedDataToGraphToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_loadedDataPairList.Count!=0)
            {
                DrawGraph(_loadedDataPairList, "Вхідні дані", Color.SaddleBrown, SymbolType.Circle, true);
            }
            else
                MessageBox.Show("Завантажте дані для побудови графіка");
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void textBoxFilePath_DoubleClick(object sender, EventArgs e)
        {
            SelectFileToLoadData();
        }

        private void Predictor_Load(object sender, EventArgs e)
        {
            textBoxColumnName.Text = _dataColumnName;
            numericUpDownAlphaValue.Value = Convert.ToDecimal(_alphaValue);
            textBoxWorkSheetName.Text = _sheetName;
            buttonSaveGeneralConfig.Enabled = false;
        }

        private void buttonSaveGeneralConfig_Click(object sender, EventArgs e)
        {
            _sheetName = textBoxWorkSheetName.Text;
            _dataColumnName = textBoxColumnName.Text;
            _alphaValue = Convert.ToDouble(numericUpDownAlphaValue.Value);
            buttonSaveGeneralConfig.Enabled = false;
        }

        private void textBoxWorkSheetName_TextChanged(object sender, EventArgs e)
        {
            buttonSaveGeneralConfig.Enabled = true;
        }

        private void textBoxColumnName_TextChanged(object sender, EventArgs e)
        {
            buttonSaveGeneralConfig.Enabled = true;
        }

        private void numericUpDownAlphaValue_ValueChanged(object sender, EventArgs e)
        {
            buttonSaveGeneralConfig.Enabled = true;
        }

        private void tabControl1_TabIndexChanged(object sender, EventArgs e)
        {

        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex == 1 && _loadedDataPairList.Count != 0&&_pane.CurveList.Count==0)
            {
                DrawGraph(_loadedDataPairList, "Вхідні дані", Color.SaddleBrown, SymbolType.Circle, true);
            }
            else if (tabControl1.SelectedIndex == 1 && _loadedDataPairList.Count == 0)
            {
                MessageBox.Show("Спочатку завантажте дані");
                tabControl1.SelectedIndex = 0;
            }
        }

        private void buttonChangeFileToLoadData_Click(object sender, EventArgs e)
        {
            SelectFileToLoadData();
        }

        private void buildModelStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (_loadedDataPairList.Count > 7)
            {
                MathAdaptiveModel math = new MathAdaptiveModel(_loadedDataPairList, _alphaValue);
                //MessageBox.Show(math.OnScreenAverages());
                //MessageBox.Show(math.PairArrayToString());
                //MessageBox.Show(math.GetSt_1());
                //MessageBox.Show(math.GetSt_2());
                DrawGraph(math.GetModel(), "Адаптивна модель", Color.Blue, SymbolType.Star);
                _prediction = math.GetPrediction();
            }
        }

        #region User Functions

        private void GetDataFromXls()
        {
            try
            {
                var connectionString = "";
                if (_fileName.Contains(".xlsx"))
                {
                    connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties=Excel 12.0;", _fileName);
                }
                else
                {
                    connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", _fileName);
                }
                var selectCommandText = string.Format("SELECT * FROM [{0}$]", _sheetName);
                var adapter = new OleDbDataAdapter(selectCommandText, connectionString);
                var ds = new DataSet();

                adapter.Fill(ds, _sheetName);

                var data = ds.Tables[_sheetName];
                //dataGridView1.DataSource = data;

                adapter.Dispose();

                if (data.Rows.Count > 7)
                {
                    _loadedDataPairList.Clear();
                    for (var i = 0; i < data.Rows.Count; i++)
                    {
                        _loadedDataPairList.Add((double)(i + 1), data.Rows[i].Field<double>(_dataColumnName));
                    }
                    MessageBox.Show(string.Format("Успішно завантажено {0} записів", _loadedDataPairList.Count));
                }
                else
                { MessageBox.Show("Недостатня для моделювання кількість записів у файлі"); }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void DrawGraph(PointPairList list, string curveName, Color curveColor, SymbolType symType, bool toClearPane=false)
        {
            if (!zedGraph.Visible)
                zedGraph.Visible = true;


            if (toClearPane)
            {
                _pane.CurveList.Clear();
            }

            //Опис графіка
            _pane.XAxis.Title.Text = "Період";
            _pane.YAxis.Title.Text = "Значення";
            _pane.Title.Text = "Графік";

            LineItem myCurve = _pane.AddCurve(curveName, list, curveColor, symType);

            // Включим сглаживание
            myCurve.Line.IsSmooth = true;

            // Обновим график
            zedGraph.AxisChange();
            zedGraph.Invalidate();
        }

        private void SelectFileToLoadData()
        {
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                _fileName = openFileDialog1.FileName;
                textBoxFilePath.Text = _fileName;
            }
        }
        #endregion

        private void forecastToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DrawGraph(_prediction, "Прогноз", Color.Green, SymbolType.Star);
        }




    }
}
